// websocketService.ts
import { Client, IMessage } from "@stomp/stompjs";
import SockJS from "sockjs-client";

class WebSocketService {
  public client: Client;

  constructor() {
    this.client = new Client({
      webSocketFactory: () => new SockJS("/ws"), // Replace with your WebSocket endpoint
      onConnect: () => {
        // console.log("Connected to WebSocket");
      },
      onDisconnect: () => {
        // console.log("Disconnected from WebSocket");
      },
      debug: () => {
        // console.log(new Date(), str);
      },
    });
  }

  // Connect to WebSocket
  connect() {
    this.client.activate();
  }

  // Disconnect from WebSocket
  disconnect() {
    this.client.deactivate();
  }

  // Subscribe to a topic
  subscribe(topic: string, onMessage: (message: IMessage) => void) {
    this.client.onConnect = () => {
      this.client.subscribe(topic, onMessage);
    };
  }

  // Send a message to a topic
  sendMessage(topic: string, message: any) {
    this.client.publish({ destination: topic, body: JSON.stringify(message) });
  }
}

const webSocketService = new WebSocketService();
export default webSocketService;
